package com.hhl.controller;

import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.hhl.dto.message.TextMessage;
import com.hhl.util.CheckUtil;
import com.hhl.util.HttpClientUtil;
import com.hhl.util.MessageUtil;
import com.hhl.util.XmlUtils;


import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class DispatCherController {
	// 服务器验证接口地址
	@RequestMapping(value = "/dispatCher", method = RequestMethod.GET)
	public String dispatCherGet(String signature, String timestamp, String nonce, String echostr) {
		// 1.验证参数
		boolean checkSignature = CheckUtil.checkSignature(signature, timestamp, nonce);
		// 2.参数验证成功之后，返回随机数
		if (!checkSignature) {
			return null;
		}
		return echostr;
	}

	// 微信动作推送
	@RequestMapping(value = "/dispatCher", method = RequestMethod.POST)
	public void dispatCherGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String ip = request.getHeader("x-forwarded-for");  
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("Proxy-Client-IP");  
	    }  
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("WL-Proxy-Client-IP");  
	    }  
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getRemoteAddr();  
	    } 
	    ip = request.getRemoteAddr();  
	    log.info(ip);
		// 1.将xml转换成Map格式
		Map<String, String> resultMap = XmlUtils.parseXml(request);
		log.info("###收到微信消息####resultMap:" + resultMap.toString());
		// 2.判断消息类型
		String msgType = resultMap.get("MsgType");
		// 3.如果是文本类型，返回结果给微信服务端
		PrintWriter writer = response.getWriter();
		// 开发者微信公众号
		String toUserName = resultMap.get("ToUserName");
		// 消息来自公众号
		String fromUserName = resultMap.get("FromUserName");
		switch (msgType) {
			case MessageUtil.RESP_MESSAGE_TYPE_TEXT:
				// 消息内容
				String content = resultMap.get("Content");
				log.info("留言内容:"+content);
				//文本消息
				final String REQESTURL = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=";
				String resultJson = HttpClientUtil.doGet(REQESTURL + content.trim());
				JSONObject jsonObject = JSONObject.parseObject(resultJson);
				Integer resultCode = jsonObject.getInteger("result");
				String msg = null;
				if (resultCode == 0) {
					String resultContent = jsonObject.getString("content");
					log.info("回复内容:"+resultContent);
					msg = setText(resultContent, toUserName,fromUserName);
				}else {
					msg = setText("我现在有点忙.稍后回复您!", toUserName,fromUserName);
				}
				writer.println(msg);
				break;
			case MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
				// 图片消息
				
				break;
			case MessageUtil.REQ_MESSAGE_TYPE_VOICE:
				//音频消息
			
			case MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
				// 地理位置消息
				System.out.println(JSONObject.toJSONString(resultMap));
				
				
			case MessageUtil.REQ_MESSAGE_TYPE_LINK:
				// 链接消息
				
			case MessageUtil.REQ_MESSAGE_TYPE_EVENT:
				// 事件推送
				// 事件类型
				String eventType = resultMap.get("Event");
				
				switch (eventType) {
					//关注
					case MessageUtil.EVENT_TYPE_SUBSCRIBE:
						msg = setText("谢谢您的关注!", toUserName,fromUserName);
						writer.println(msg);
						break;
					//取消关注
					case MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
						msg = setText("欢迎下一次您的到来!", toUserName,fromUserName);
						writer.println(msg);
						break;
					//菜单点击事件
					case MessageUtil.EVENT_TYPE_CLICK:
						if(resultMap.get("EventKey").equals("GYWM")){
							msg = setText("暂时没有我们的动态！", toUserName,fromUserName);
							writer.println(msg);
						}else if(resultMap.get("EventKey").equals("KEY_MZ_KNOW")){
							msg = setText("没有测试图文消息！", toUserName,fromUserName);
							writer.println(msg);
						}else if(resultMap.get("EventKey").equals("KEY_RY_KNOW")){
							msg = setText("没有测试文本消息！", toUserName,fromUserName);
							writer.println(msg);
						}
						
						break;
						
					case MessageUtil.EVENT_TYPE_LOCATION:
						String locationUrl="http://apis.map.qq.com/ws/location/v1/ip?ip=183.228.184.150&key=CRPBZ-3DS63-Q3A3D-YX7F6-23FRJ-37FWB";
						locationUrl="http://apis.map.qq.com/ws/geocoder/v1/?location="+resultMap.get("Latitude")+","+resultMap.get("Longitude")+"&get_poi=0&key=CRPBZ-3DS63-Q3A3D-YX7F6-23FRJ-37FWB";
						String locationResult = HttpClientUtil.doGet(locationUrl);
						JSONObject jsonLocation = JSONObject.parseObject(locationResult);
						if(jsonLocation.getInteger("status")==0){
							String location = jsonLocation.toJSONString(jsonLocation);
							log.info(location);
							String weizhi = JSONObject.parseObject(JSONObject.parseObject(jsonLocation.getString("result")).getString("formatted_addresses")).getString("recommend");
							log.info("精度:"+resultMap.get("Latitude")+"维度："+resultMap.get("Longitude")+"大致地址:"+weizhi);
							String msg1 = setText("精度:"+resultMap.get("Latitude")+"维度："+resultMap.get("Longitude")+"大致地址:"+weizhi,toUserName,fromUserName);
							writer.println(msg1);
						}
						
						break;
					
					default:
						break;
				}
				
			default:
				break;
		}
		writer.close();
	}

	public String setText(String content, String fromUserName, String toUserName) {
		TextMessage textMessage = new TextMessage();
		textMessage.setContent(content);
		textMessage.setMsgType("text");
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setFromUserName(fromUserName);
		textMessage.setToUserName(toUserName);
		// 将实体类转换成xml格式
		String msg = XmlUtils.messageToXml(textMessage);
		return msg;
	}
}
